package com.xixilala.zh_ad_style

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

/**
 * Created by hc on 2021.2.18.
 */
class ADImageView : androidx.appcompat.widget.AppCompatImageView {
    private var emptyRadius = 0F
    private var image: Bitmap  ?= null
    private val mPaint = Paint().apply {  }

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    fun setImage(image: Bitmap) {
        this.image = image
        invalidate()
    }

    fun setImage( image: Int) {
        this.image = BitmapFactory.decodeResource(resources, image)
        invalidate()
    }

    fun setEmptyImageRadius(emptyRadius:Float) {
        this.emptyRadius = emptyRadius
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        canvas?.let {canvas->

            image?.let {image->

                // 1.图层混合模式使用时必须禁止硬件加速
                setLayerType(View.LAYER_TYPE_SOFTWARE,null)
                // 2.离屏绘制
                val layerId = canvas.saveLayer(
                    0F,
                    0F,
                    width.toFloat(),
                    height.toFloat(),
                    mPaint,
                    Canvas.ALL_SAVE_FLAG
                )

                mPaint.style = Paint.Style.STROKE
                canvas.drawBitmap(image, 0F,0F, mPaint)
                mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.XOR)
                mPaint.color = Color.WHITE
                mPaint.style = Paint.Style.FILL_AND_STROKE
                canvas.drawCircle(0F,0F,emptyRadius,mPaint)
                mPaint.xfermode = null

                canvas.restoreToCount(layerId)

            }
        }

    }
}